//
//  CountryViewController.m
//  weimao
//
//  Created by 黄佳峰 on 16/2/21.
//  Copyright © 2016年 黄佳峰. All rights reserved.
//

#import "CountryViewController.h"
#import "HttpManager.h"
#import "NSString+PinYin.h"

@interface CountryViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong) UITableView * tableView;

@property(nonatomic,strong) NSMutableArray * dataArr;

@property(nonatomic,strong)NSArray * carArr;

@property(nonatomic,strong)NSString*str;
@property(nonatomic,strong)NSString*str1;
@property(nonatomic,strong)NSDictionary *dic;
@end

@implementation CountryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataArr = [[NSMutableArray alloc]init];
    
    [self makeNaviButton];
    
    [self getDatas];
    
    [self createTableView];
}

-(void)makeNaviButton{
    
    self.title=@"CHOOSE THE COUNTRY";
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem*item= [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem=item;

}


#pragma mark 返回事件
-(void)comeBack{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)preData
{
    NSArray * popularArr = [NSArray arrayWithObjects:@"United States",@"Puerto Rico",@"United Kingdom",@"Ireland",@"Australia",@"New Zealand",@"Canada",@"Germany",@"France",@"Italy",@"Spain",@"Philippines",@"Singapore", nil];
    NSMutableArray * firstModel = [[NSMutableArray alloc]init];
    for (NSString * str in popularArr) {
        [firstModel addObject:str];
    }
    NSMutableDictionary * firstDic = [[NSMutableDictionary alloc]init];
    [firstDic setObject:@"#" forKey:@"Title"];
    [firstDic setObject:firstModel forKey:@"Arr"];
    
    [_dataArr addObject:firstDic];
    
    for (char i = 'A'; i <= 'Z'; i++)
    {
        
        NSString * str = [NSString stringWithFormat:@"%c",i];
        
        NSMutableArray * carMuArr = [[NSMutableArray alloc]init];
        
        
        
        for (NSString * carName in _carArr)
        {
            if ([[carName getFirstLetter] isEqualToString:str])
            {
                [carMuArr addObject:carName];
            }
        }
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:str forKey:@"Title"];
        [dic setObject:carMuArr forKey:@"Arr"];
        
        [_dataArr addObject:dic];
    }
//    NSLog(@"%@",_dataArr);
}

- (void)createTableView
{
    _tableView = ({
        UITableView * tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, ACTUAL_HEIGHT(0), KScreenWidth, KScreenHeight) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView;
    });
    [self.view addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary * dic = _dataArr[section];
    NSArray * arr = dic[@"Arr"];
    return arr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"myCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSDictionary * dic = _dataArr[indexPath.section];
    NSArray * arr = dic[@"Arr"];
    cell.textLabel.text = arr[indexPath.row];
    cell.textLabel.textColor = [UIColor grayColor];
    return cell;
}


//设置组名
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"Popular Countries";
    }
    NSDictionary * dic = _dataArr[section];
    return dic[@"Title"];
}

//设置索引名
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    tableView.sectionIndexColor = [UIColor blueColor];
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    for (NSDictionary * dic in _dataArr)
    {
        [arr addObject:dic[@"Title"]];
    }
    return arr;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //NSLog(@"%lu    %lu",indexPath.section,indexPath.row);
    
    NSDictionary * dic = _dataArr[indexPath.section];
    
    NSArray * arr = dic[@"Arr"];
    
    _str= arr[indexPath.row];
    _str1=_dic[_str];
    
    if ([self.delegate respondsToSelector:@selector(delegateForBack0:And:)]) {
        [self.delegate delegateForBack0:_str And:_str1];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dismissTo{
    if ([self.delegate respondsToSelector:@selector(delegateForBack0:And:)]) {
        [self.delegate delegateForBack0:_str And:_str1];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if ([self.delegate respondsToSelector:@selector(delegateForBack0:And:)]) {
        [self.delegate delegateForBack0:_str And:_str1];
    }

}

-(void)getDatas{
//  http://viprunningonline.com/api/index.php? main_page=countries
    NSMutableString *urlStr=[NSMutableString stringWithFormat:@"%@", HTTP_ADDRESS];
    NSDictionary*params=@{@"main_page":@"countries"};
    
    HttpManager *manager=[[HttpManager alloc]init];
    [manager getDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
//        NSLog(@"country>>>>>>%@",data);
        if ([number isEqualToString:@"1"]) {
            self.dic=[NSDictionary dictionary];
            _dic=data[@"data"][@"countries"];
            _carArr=_dic.allKeys;
            
            [self preData];
            [self.tableView reloadData];
            
        }else{
            [JRToast showWithText:[data objectForKey:@"errorMessage"]];
        }
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
